package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.baiduyun.utils.ExamineUtil;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoExamineService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: WmNewsAutoExamineServiceImpl
 * Description:
 * date: 2023/8/10 0010 19:34
 *
 * @author zHan
 */
@Service
@Slf4j
@GlobalTransactional    // 分布式事务
public class WmNewsAutoExamineServiceImpl implements WmNewsAutoExamineService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private ExamineUtil examineUtil;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章自动审核
     *
     * @param id
     */
    @Override
    @Async  // 异步调用的方法
    public void autoExamineWmNews(Integer id) {
        // 校验参数
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        // 文章不存在
        if (wmNews == null) {
            throw new RuntimeException("文章不存在");
        }
        // 文章状态为待审核状态生效
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            // 从内容中抽取纯文本和图片
            Map<String, Object> textAndImgsMap = handleTextAndImgs(wmNews);
            String text = String.valueOf(textAndImgsMap.get("text"));
            // 自管理敏感词过滤
            boolean isPassSensitive = autoExamineSensitive(text, wmNews);
            if (!isPassSensitive) return;

            // 审核文本内容，百度云
            boolean isPassText = autoExamineText(text, wmNews);
            if (!isPassText) return;

            // 审核图片，百度云
            List<String> images = (List<String>) textAndImgsMap.get("images");
            boolean isPassImages = autoExamineImages(images, wmNews);
            if (!isPassImages) return;

            // 审核成功，保存app端的相关文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("文章审核，保存app端的相关文章数据失败");
            }
            // 回填articleId
            wmNews.setArticleId((Long) responseResult.getData());
            // 修改文章状态为已发布
            updateWmNewsStatus(wmNews, WmNews.Status.PUBLISHED.getCode(), "审核成功");
        }
    }

    /**
     * 自管理敏感词过滤
     *
     * @param text
     * @param wmNews
     * @return
     */
    private boolean autoExamineSensitive(String text, WmNews wmNews) {
        boolean flag = true;
        if (text.length() == 0) {
            return flag;
        }
        // 获取所有的敏感词
        List<WmSensitive> wmSensitives =
                wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        // 转换为string类型
        List<String> sensitivesList =
                wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        // 初始化敏感词库
        SensitiveWordUtil.initMap(sensitivesList);
        // 匹配是否存在敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (map.size() > 0) {
            flag = false;
            updateWmNewsStatus(wmNews, WmNews.Status.FAIL.getCode(), "当前文章存在违规内容" + map);
        }
        return flag;
    }

    /**
     * 保存app端的相关文章数据
     *
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        // 属性拷贝
        BeanUtils.copyProperties(wmNews, dto);
        // 文章布局
        dto.setLayout(wmNews.getType());
        // 频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(dto.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        // 作者id和作者名称
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId().longValue());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }
        // 文章id，如果审核通过，有文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        // 创建时间
        dto.setCreatedTime(new Date());
        // 执行方法并返回
        return articleClient.saveArticle(dto);
    }

    /**
     * 审核图片
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean autoExamineImages(List<String> images, WmNews wmNews) {
        // 默认为审核通过
        boolean flag = true;

        if (images == null || images.size() == 0) {
            return flag;
        }
        // 图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        // 循环审核图片
        for (String image : images) {
            try {
                // minio中下载图片
                byte[] bytes = fileStorageService.downLoadFile(image);
                // tess4j 图片识别
                ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                String result = tess4jClient.doOCR(bufferedImage);
                // 过滤文字
                boolean isPassSensitive = autoExamineSensitive(result, wmNews);
                if (!isPassSensitive) return isPassSensitive;

                // 调用百度云审核文本
                Map imgMap = (examineUtil.imgExamine(bytes));
                if (imgMap != null) {
                    // 审核失败
                    if (imgMap.get("code").equals("block")) {
                        flag = false;
                        updateWmNewsStatus(wmNews, WmNews.Status.FAIL.getCode(), "当前文章存在违规内容");
                    }
                    // 不确定，需要人工审核，修改文章状态
                    if (imgMap.get("code").equals("suspected")) {
                        flag = false;
                        updateWmNewsStatus(wmNews, WmNews.Status.ADMIN_AUTH.getCode(),
                                "当前文章存在不确定内容");
                    }
                }
            } catch (Exception e) {
                flag = false;
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 审核文本内容
     *
     * @param text
     * @param wmNews
     * @return
     */
    private boolean autoExamineText(String text, WmNews wmNews) {
        // 默认为审核通过
        boolean flag = true;
        // 文本内容为空，直接返回
        if (text.length() == 0) {
            return flag;
        }
        try {
            // 调用百度云审核文本
            Map textMap = examineUtil.textExamine(text);
            if (textMap != null) {
                // 审核失败
                if (textMap.get("code").equals("block")) {
                    flag = false;
                    updateWmNewsStatus(wmNews, WmNews.Status.FAIL.getCode(), "当前文章存在违规内容");
                }
                // 不确定，需要人工审核，修改文章状态
                if (textMap.get("code").equals("suspected")) {
                    flag = false;
                    updateWmNewsStatus(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "当前文章存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改文章状态
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNewsStatus(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从内容中抽取纯文本和图片
     *
     * @param wmNews
     */
    private Map<String, Object> handleTextAndImgs(WmNews wmNews) {
        // 获取标题、内容和封面
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String images = wmNews.getImages();
        // 存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();
        // 存储集合
        List<String> imgUrlList = new ArrayList<>();
        // 判断标题是否为空
        if (StringUtils.isNotBlank(title)) {
            // 内容文本
            stringBuilder.append(title).append("-");
        }
        // 判断内容是否为空
        if (StringUtils.isNotBlank(content)) {
            List<Map> mapList = JSONArray.parseArray(content, Map.class);
            mapList.stream().forEach(map -> {
                if (map.get("type").equals("text")) {
                    // 内容文本
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")) {
                    imgUrlList.add(String.valueOf(map.get("value")));
                }
            });
        }
        // 提取文章封面
        if (StringUtils.isNotBlank(images)) {
            // ，分割的转换成集合
            imgUrlList.addAll(Arrays.asList(images.split(",")));
        }
        // 存入map中
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("text", stringBuilder);
        resultMap.put("images", imgUrlList);
        return resultMap;
    }
}
